import { Component, OnInit, ViewChild, OnDestroy } from '@angular/core';
import { _HttpClient, ModalHelper } from '@delon/theme';
import { SimpleTableColumn, SimpleTableComponent } from '@delon/abc';
import { NzMessageService, NzModalService, NzTabChangeEvent, UploadFile, NzNotificationService } from 'ng-zorro-antd';
import { CommService } from 'app/service/comm/comm.service';
import { Constant, ServiceResult } from '@core/constant';
import { EmitterService } from 'app/service/emit.service';
import { Router } from '@angular/router';
import { ProductService } from '../../../service/prod/product.service';
import { catchError } from 'rxjs/operators';
import { of } from 'rxjs';
import { GoodsPriceModalComponent } from 'app/routes/prod/goods-price/goods-price-modal.component';
import { TranslateService } from '@ngx-translate/core';
import { Timeout } from '@shared/descriptor/timeout';




@Component({
  selector: 'product-list',
  templateUrl: './product-list.component.html',
  styleUrls: ['./product-list.component.less']
})
export class ProdProductListComponent implements OnInit, OnDestroy {
  // region 公共字段

  visible = false;
  // pageSize
  ps = 10;
  // 搜索表单
  q: any = {
    productCd: null,
    brand: null,
    userGroup: null,
    year: null,
    isAd: null,
    isCm: null,
    status: null
  };

  loading = false;
  // 表格组件
  @ViewChild('st') st: SimpleTableComponent;
  // 表格数据url
  url = this.productService.list();
  // region end

  // 搜索区域显示/隐藏标记
  // 显示图片
  previewVisible = false;
  // 大图地址
  previewImage = '';
  imgSuffix = '';

  years = [];
  userGroups = [];
  brands = [];
  isAds = [{ text: '广告款', value: this.cnt.BoolUtil.TRUE}, { text: '普通款', value: this.cnt.BoolUtil.FALSE }];
  isCms = [{ text: '是', value: this.cnt.BoolUtil.TRUE}, { text: '否', value: this.cnt.BoolUtil.FALSE }];
  seasons = [];
  checkedList = [];
  data = [];

  uploadUrl = this.productService.uploadProds();
  uploadDateUrl = this.productService.batchRepdate();


  columns: SimpleTableColumn[] = [
    { title: '', index: 'key', type: 'checkbox' },
    { title: '订单编号', index: 'orderNo' },
    { title: '客户姓名 <br> 订单类型 <br>  联系电话', index: 'cusName'},
    { title: '车辆信息', index: 'fiName' },
    { title: '期数 <br> 融资额 ', index: 'fiAmount' },
    { title: '录入业务员 <br> 产品种类 <br> 合作伙伴' , index: 'paInfo' },
    { title: '订单提交时间', index: 'orderDate' },
    { title: '审批人员', index: 'orderUser' },
    { title: '订单状态', index: 'bpmStatus' },
    // { title: '年份', index: 'year' },
    // { title: '广告款', index: 'isAd', render: 'isAd' },
    // { title: '定制', index: 'isCm', render: 'isCm' },
    // { title: '状态', index: 'status', type: 'badge', badge: {
    //     '1': { text: '上架', color: 'success' },
    //     '0': { text: '下架', color: 'error' }
    //   }
    // },
    {
        title: '操作',
        buttons: [
            {
              text: '编辑',
              type: 'link',
              click: (record: any) => this.router.navigate(['/prod/product/edit/'+record.id])
            },
            {
              text: '查看',
              click: (record: any) => this.view(record)
           }
        ]
    }
  ];

  constructor(
    private trans: TranslateService,
    public http: _HttpClient,
    public msg: NzMessageService,
    private modalSrv: ModalHelper,
    private comm: CommService,
    private cnt: Constant,
    private productService: ProductService,
    private emit: EmitterService,
    private router: Router,
    private modalService: NzModalService,
    private notice: NzNotificationService,
  ) {}
  syncing = false;
  lastDate = null;

  ngOnDestroy() {
    if (this.inter) {
      clearInterval(this.inter);
    }
  }

  inter
  ngOnInit() {
    this.imgSuffix = this.comm.getGoodsUrl();
    this.loadUserGroup();
    this.loadYears();
    this.loadBrands();
    this.loadSeasons();
    this.emit.getMessage().subscribe(data => {
      if (data.text === 'RELOAD_GOODS_LIST') {
        this.st.load(1, this.q);
      }
    })

    // 每隔5s获取同步状态
    this.inter = setInterval(() => {
      this.productService.getSyncLog().pipe(catchError(err => {
        return of(err)
      })).subscribe(data => {
        if (data.status === 200) {
          if (data.data) {
            if (data.data.last_date) {
              this.lastDate = data.data.last_date;
            }
            if (data.data.status === 1) {
              this.syncing = true;
            } else {
              this.syncing = false;
            }
          } else {
            this.syncing = false;
          }
        } else {
          this.syncing = false;
        }
      })
    }, 5000);
  }

  fullChange(val: boolean) {
    // this.scroll = val ? { y: '350px' } : { y: '230px' };
  }

  // 加载产品季节
  loadSeasons() {
    this.seasons = [];
    this.comm.getSeasons().subscribe(data => {
      const ret: ServiceResult = <ServiceResult> data;
      if (ret.status === 200) {
          for (const row of ret['data']['rows']) {
              this.seasons.push({ text: row.labelDefault, value: row.value });
          }
      }
    })
  }

  loadYears() {
    let lang = this.trans.currentLang || this.trans.defaultLang;
    this.years = [];
    this.comm.getYear().subscribe(data => {
      const ret: ServiceResult = <ServiceResult> data;
      if (ret.status === 200) {
          for (const row of ret['data']['rows']) {
              this.years.push({ text: lang === 'en' ? row.labelEnUs : row.labelDefault, value: row.value });
          }
      }
    })
  }

   // 加载品牌列表
  loadBrands() {
    let lang = this.trans.currentLang || this.trans.defaultLang;
    this.brands = [];
    this.comm.getBrand().subscribe(data => {
      const ret: ServiceResult = <ServiceResult> data;
      if (ret.status === 200) {
          for (const row of ret['data']['rows']) {
              this.brands.push({ text: lang === 'en' ? row.labelEnUs : row.labelDefault, value: row.value });
          }
      }
    })
  }

  loadUserGroup() {
    let lang = this.trans.currentLang || this.trans.defaultLang;
    this.userGroups = [];
    this.comm.getUserGroup().subscribe(data => {
      const ret: ServiceResult = <ServiceResult> data;
      if (ret.status === 200) {
          for (const row of ret['data']['rows']) {
              this.userGroups.push({ text: lang === 'en' ? row.labelEnUs : row.labelDefault, value: row.value });
          }
      }
    })
  }

  change(args: NzTabChangeEvent) {
        switch (args.index) {
          case 0:
            this.q.status = null;
            break;
          case 1:
            this.q.status = this.cnt.BoolUtil.TRUE;
            break;
          case 2:
            this.q.status = this.cnt.BoolUtil.FALSE;
            break;
          default:
            break;
        }
      this.st.load(1, this.q);
  }

  showImage(src) {
    this.previewImage = src;
    this.previewVisible = true;
  }

  checkboxChange(list: any[]) {
    this.checkedList = list;
  }

  gotoAdd() {
    setTimeout(() => {
      this.router.navigate(['/prod/product/add']);
    }, 500);
  }

  @Timeout(500)
  gotoImg() {
    this.router.navigate(['/prod/product/upload']);
  }


  batchUnder() {
    let ids = this.checkedList.map(v => { return v.id });
    this.productService.batchUnder(ids.toString()).pipe(
      catchError(err => {
        return of(err);
      })
    ).subscribe(data => {
      this.st.reload();
      this.checkedList = [];
    })
  }

  batchUp() {
    let ids = this.checkedList.map(v => { return v.id });
    this.productService.batchSale(ids.toString()).pipe(
      catchError(err => {
        return of(err);
      })
    ).subscribe(data => {
      this.st.reload();
      this.checkedList = [];
    })
  }


  /**
   * 批量下架
   */
  showUnderConfirm(): void {
    if (this.checkedList.length == 0) {
      this.msg.warning('请选择产品');
      return;
    }

    this.modalService.confirm({
      nzTitle     : `警告`,
      nzContent   : `确定<span class="border-bottom-1 border-error">下架</span>选中的<b style="color: red;"> ${this.checkedList.length}</b> 项产品?`,
      nzOkText    : '确定',
      nzOkType    : 'danger',
      nzOnOk      : () => this.batchUnder(),
      nzCancelText: '取消'
    });
  }

  showUpConfirm(): void {
    if (this.checkedList.length == 0) {
      this.msg.warning('请选择产品');
      return;
    }

    this.modalService.confirm({
      nzTitle     : `警告`,
      nzContent   : `确定<span class="border-bottom-1 border-error">上架</span>选中的<b style="color: red;"> ${this.checkedList.length}</b> 项产品?`,
      nzOkText    : '确定',
      nzOkType    : 'danger',
      nzOnOk      : () => this.batchUp(),
      nzCancelText: '取消'
    });
  }

  showPrices(mode): void {
    if (this.checkedList.length == 0) {
      this.msg.warning('请选择产品');
      return;
    }
    let ids = this.checkedList.map(v => { return v.id });
    const modal = this.modalService.create({
      nzWidth: '800px',
      nzStyle: { top: '20px' },
      nzTitle: null,
      nzContent: GoodsPriceModalComponent,
      nzComponentParams: {
        ids: ids,
        mode: mode
      },
      nzCancelText: '取消',
      nzOkText: '确定',
      nzOnOk: (priceModal) => {
        let list = [];
        for (let i = 0; i < priceModal.data.length; i++) {
          let newSalePrice = priceModal.getNewPrice(1, priceModal.data[i]);
          let newPurchasePrice = priceModal.getNewPrice(2, priceModal.data[i]);
          let newPrice = priceModal.getNewPrice(3, priceModal.data[i]);
          list.push({id: priceModal.data[i].id, mode: mode, tradePrice: newSalePrice, retailPrice: newPurchasePrice, marketPrice: newPrice});
        }
        this.productService.batchPrice(list).pipe(
          catchError(err => {
            return of(err);
          })
        ).subscribe(data => {
          if (data.status === 200) {
            this.msg.success("保存成功");
            modal.destroy();
            this.checkedList = [];
            this.st.reload();
          } else {
            this.msg.error("保存失败");
          }
        })
        return false;
      }
    });
  }

  export() {
    if (this.checkedList.length > 0) {
      this.st.export(this.checkedList, { filename: '商品清单.xlsx' });
    } else {
      let param = `?pageNumber=1&pageSize=0`;
      if (this.st.extraParams.productCd) {
        param += "&productCd=" + this.st.extraParams.productCd;
      }
      if (this.st.extraParams.brand) {
        param += "&brand=" + this.st.extraParams.brand;
      }
      if (this.st.extraParams.userGroup) {
        param += "&userGroup=" + this.st.extraParams.userGroup;
      }
      if (this.st.extraParams.year) {
        param += "&year=" + this.st.extraParams.year;
      }
      if (this.st.extraParams.isAd) {
        param += "&isAd=" + this.st.extraParams.isAd;
      }
      if (this.st.extraParams.isCm) {
        param += "&isCm=" + this.st.extraParams.isCm;
      }
      if (this.st.extraParams.status) {
        param += "&status=" + this.st.extraParams.status;
      }
      this.st.export(this.url + param, { filename: '商品清单.xlsx' });
    }
  }

  selectProd: {[propName: string]: any;} = {}
  selectUrl = null;

  view(record) {
    this.productService.getProduct(record.id).pipe(
      catchError(err => {
        return of(err);
      })
    ).subscribe(data => {
      this.selectProd = data.data;
      // 拼接图片地址
      this.selectUrl = this.comm.getGoodsUrl() + this.selectProd.img;
      this.visible = true;
    })

  }

  close(): void {
    this.visible = false;
  }

  // setRepdate() {
  //   if (this.checkedList.length == 0) {
  //     this.msg.warning('请选择产品');
  //     return;
  //   }
  //   if (!this.repdate) {
  //     this.msg.warning('请输入预计的补货日期');
  //     return false;
  //   }
  //   let ids = this.checkedList.map(v => { return v.id });
  //   this.productService.batchRepdate(ids.toString(), this.repdate).pipe(
  //     catchError(err => {
  //       return of(err);
  //     })
  //   ).subscribe(data => {
  //     if (data.status === 200) {
  //       this.msg.success('操作成功');
  //       this.repdate = null;
  //     } else {
  //       this.msg.error(data.message);
  //     }
  //   })
  // }

  cancel() {
    this.repdate = null;
  }
  repdate = null;



  uploadProd(info: { file: UploadFile }) {
    if (info.file.status === 'uploading') {
        this.loading = true;
    }
    if (info.file.status === 'done') {
        this.loading = false;
        this.notice.create('success', 'Success', info.file.response.data['successTip']);
        if (undefined !== info.file.response.data['failTip']) {
          this.notice.create('info', 'Info', info.file.response.data['failTip']);
        }
        this.st.load();
    }
    if (info.file.status === 'error') {
        this.loading = false;
      this.notice.create('error', 'Error', info.file.response.msg);
    }
  }


  syncStock() {
    this.productService.doSync().pipe(catchError(err => {
      return of(err)
    })).subscribe(data => {
        this.syncing = true;
    })
  }



}
